package com.gws.ievent.common.utils;

import org.springframework.cglib.beans.BeanMap;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author song
 * @date 2022/10/22 8:18
 */
public class StringUtil {

    /**
     * 去除字符串末尾字符
     *
     * @param str
     * @param mask
     * @return
     */
    public static String trimEnd(String str, String mask) {
        if ((str == null) || (str.length() == 0)) {
            return str;
        }

        if (str.endsWith(mask)) {
            return str.substring(0, str.lastIndexOf(mask));
        }
        return str;
    }


    /**
     * 去除字符串开头字符
     *
     * @param str
     * @param mask
     * @return
     */
    public static String trimStart(String str, String mask) {
        if ((str == null) || (str.length() == 0)) {
            return str;
        }

        if (str.startsWith(mask)) {
            return str.substring(str.indexOf(mask) + mask.length());
        }
        return str;
    }


    /**
     * 把map转为 k=v&k2=v2 get请求参数字符串
     *
     * @param params
     * @return
     */
    public static String httpBuildQuery(Map<String, String> params) {
        StringBuilder reString = new StringBuilder();
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value != null) {
                reString.append(key).append("=").append(value).append("&");
            }
        }

        String str = trimEnd(reString.toString(), "&");

        try {
            //将得到的字符串进行处理得到目标格式的字符串
            String utf8Str = URLEncoder.encode(str, "utf-8");
            return utf8Str.replace("%3D", "=").replace("%26", "&");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }


    /**
     * 把对象转为map<String, String>
     *
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> beanToStringMap(T bean) {
        Map<String, String> map = new HashMap<>(16);
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if (beanMap.get(key) != null) {
                    map.put(key.toString(), beanMap.get(key).toString());
                }
            }
        }
        return map;
    }

}
